<template>
  <div>
    <x-Table
      :loading="loading"
      :table-data="tableData"
      :options-data="options"
      :pagination="pagination"
      :rule-form="ruleForms"
      @handleAdd="handleAdd"
      @handlePaginationCurrentChange="handlePaginationCurrentChange"
      @handlePaginationSizeChange="handlePaginationSizeChange"
      @handleHeardDel="handleHeardDel"
      @searchForm="searchForm"
      @resetForm="resetForm"

    >
    </x-Table>
    <!--    弹窗区域-->
    <el-dialog
      v-dialog-drag
      :title="alertTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="45%"
    >
      <form-create
        v-model="fapi"
        :rule="rule"
        :option="option"
        :value.sync="formParam"
        @submit="onSubmit"
      >
      </form-create>
    </el-dialog>
    <!--    end-->

    <!--    弹窗区域-->
    <el-dialog
      v-dialog-drag
      title="分配题目"
      :visible.sync="selectTopic"
      :close-on-click-modal="false"
      width="65%"
    >
      <div>
        <div style="display: flex;justify-content: space-around">
          <div>
            题目数量:<span style="font-weight: bold;font-size: 18px">{{ topic_num }}</span>
          </div>
          <div>
            题目分数:<span style="font-weight: bold;font-size: 18px">{{ topic_score }}</span>
          </div>
        </div>
        <paper
          @PaginationSizeChangePaper="PaginationSizeChangePaper"
          @PaginationCurrentChangePaper="PaginationCurrentChangePaper"
          :twoPagination="twoPagination"
          :selectValue="selectValue"
          v-if="selectTopic" ref="Pager"
          @selectionChangePager="selectionChangePager"/>
      </div>
      <div style="display: flex;justify-content: center">
        <el-button @click="updateData" type="primary" round>更新/保存</el-button>
      </div>
    </el-dialog>
    <!--    end-->
  </div>
</template>

<script>
import paper from './components/paper';

let _this;
export default {
  components: {paper},
  data() {
    return {
      searchParams: {},//搜索对象
      twoPagination: {
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
      },
      selectList: [],//选择的数据
      selectValue: [],//编辑时表单选择数据
      topic_num: 0,
      topic_score: 0,
      selectTopic: false,
      loading: true,
      row: null, //当前选择数据
      ruleForms: {
        title: {label: "试卷名称", prop: "title", type: "text"},
        pattern: {label: "类型", prop: "pattern", type: "select",select:[{label:'考试',value:'1'},{label:'作业',value:'0'}]},
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [10, 20, 50, 100],
      }, //分页参数
      otherParam: {
        halfCheckedKeys: [],
      }, //如果有其他情况会拼接这个参数
      fapi: {},
      formParam: {},
      rule: [
        {
          "type": "input",
          "field": "title",
          "title": "试卷名称",
          "info": "",
          "_fc_drag_tag": "input",
          "hidden": false,
          "display": true,
          "validate": [
            {
              "trigger": "submit",
              "mode": "required",
              "message": "请输入试卷名称",
              "required": true,
              "type": "string"
            }
          ]
        },
        {
          "type": "select",
          "field": "pattern",
          "title": "类型",
          "info": "",
          "effect": {
            "fetch": ""
          },
          "options": [
            {
              "value": '考试',
              "label": "考试"
            },
            {
              "value": '作业',
              "label": "作业"
            }
          ],
          "_fc_drag_tag": "select",
          "hidden": false,
          "display": true,
          "value": '考试',
          "validate": [
            {
              "trigger": "submit",
              "mode": "required",
              "message": "请选择类型",
              "required": true,
              "type": "string"
            }
          ]
        }
      ],
      option: {
        form: {
          inline: false,
          labelPosition: "right",
          size: "small",
          labelWidth: "125px",
          hideRequiredAsterisk: false,
          showMessage: true,
          inlineMessage: false,
        },
        resetBtn: true,
      },
      dialogVisible: false,
      alertTitle: "添加",
      tableData: [],
      options: {
        fields: {
          id: {label: "ID", prop: "id", width: "120", order: true},
          title: {label: "试卷名称", prop: "title"},
          pattern: {
            label: "试卷类型",
            prop: "pattern",
            type: 'tag',
            options: [{label: '作业', attr: 'info'}, {label: '考试', attr: 'primary'}]
          },
          score: {label: "分数", prop: "score", type: 'tag'},
          topic_num: {label: "题目数量", prop: "topic_num"},
          create_time: {label: "创建时间", prop: "create_time", order: true},
          button: {
            label: "操作",
            width: "150",
            type: "func",
            fixed: true,
            options: [{
              label: '分配题目', button: async function (scope) {
                console.log(scope['row'])
                _this.row = scope["row"];
                _this.topic_num = 0;
                _this.topic_score = 0;
                _this.selectList = [];
                _this.twoPagination.pageSize = parseInt(scope['row']['page_size'] == null ? 10 : scope['row']['page_size'])
                _this.twoPagination.currentPage = parseInt(scope['row']['page'] == null ? 1 : scope['row']['page'])
                _this.selectValue = scope['row']['questions'] == null ? [] : scope['row']['questions'].split(',');
                _this.selectTopic = true;
                setTimeout(() => {
                  _this.topic_score = scope['row']['score'] == null ? 0 : scope['row']['score'];
                },2000)

              }
            }],
            edit: function (scope) {
              setTimeout(() => {
                _this.fapi.setValue("title", scope["row"].title);
                _this.fapi.setValue("pattern", scope["row"].pattern);
              }, 0);
              _this.row = scope["row"];
              _this.alertTitle = "编辑";
              _this.dialogVisible = true;
            },
            del: function (scope) {
              _this.deleteDate(scope["row"].id);
            },
          },
        },
      },
    };
  },
  methods: {

    resetForm:function (){
      _this.searchParams = {};
    },

    PaginationSizeChangePaper:function (val){
      _this.twoPagination.pageSize = val
    },

    PaginationCurrentChangePaper:function (val){
      _this.twoPagination.currentPage = val
    },

    //选择题目保存
    updateData: function () {
      let data = [];
      _this.selectList.forEach((item, index) => {
        data.push(item.id);
      })

      this.creatPaperOrUpdate({
        score: _this.topic_score,
        topic_num: _this.topic_num,
        questions: data.join()
      });
    },

    /**
     * 去重
     * @param arr
     * @returns {*[]}
     */
    unique: function (arr) {
      let newArr = [];
      for (let i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
          newArr.push(arr[i])
        }
      }
      return newArr;
    },
    /**
     * 表单选择回调
     */
     async selectionChangePager (val) {
      _this.topic_score = 0;
      _this.selectList = val;
      _this.selectList.forEach((item, index) => {
        if (item.score != null) {
          _this.topic_score += item.score;
        }
      })
      _this.topic_num = _this.selectList.length;
      return true;
    },

    handlePaginationCurrentChange: function (val) {
      _this.loading = true;
      _this.pagination["currentPage"] = val;
      _this.getDateList(_this.searchParams);
    },

    handlePaginationSizeChange: function (val) {
      _this.loading = true;
      _this.pagination["pageSize"] = val;
      _this.getDateList(_this.searchParams);
    },

    /**
     * 查询所有专业数据
     */
    getDateList: function (param) {
      _this.loading = true;
      _this.$store
        .dispatch("exam/getPaperList",param ? {
          title:param['title'],
          pattern:param['pattern'],
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        }:{
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        })
        .then(() => {
          _this.loading = false;
          _this.dialogVisible = false;
          _this.selectTopic = false;
          let data = this.$store.state.exam.paperList;
          this.tableData = data.data;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        });
    },


    /**
     * 批量删除
     */
    handleHeardDel: function (val) {
      let del = [];
      val.forEach((item, index) => {
        del.push(item.id);
      });
      _this.deleteDate(del);
    },


    creatPaperOrUpdate: function (param) {
      console.log(_this.twoPagination.currentPage)
      _this.$store
        .dispatch("exam/creatPaperOrUpdate", {
          id: _this.row == null ? '' : _this.row.id,
          title: param["title"],
          pattern: param["pattern"],
          page: _this.twoPagination.currentPage,
          page_size: _this.twoPagination.pageSize,
          score: param["score"],
          topic_num: param["topic_num"],
          questions: param["questions"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.$message.success(msg);
            _this.getDateList();
          } else {
            _this.$message.error(msg);
          }
        });
    },
    /**
     * 表单提交回调
     */
    onSubmit: function (val) {
      _this.creatPaperOrUpdate(val)
    },


    searchForm: function (val) {
      _this.searchParams = val;
      _this.getDateList(val);
    },


    deleteDate: function (val) {
      _this.$store
        .dispatch("exam/deletePaper", {
          id: val,
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getDateList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     *  表单导航栏添加点击
     */
    handleAdd: function () {
      _this.alertTitle = "添加";
      this.dialogVisible = true;
      this.row = null;
    },
  },
  watch: {
    dialogVisible(newVal) {
      setTimeout(() => {
        if (!newVal) {
          _this.fapi.resetFields(); //清空数据
          _this.fapi.setValue('content', '');
        }
      }, 0);
    },

  },
  created() {
    _this = this;
  },
  mounted() {
    this.getDateList();
  },
};
</script>

<style scoped></style>
